package com.firesrc.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.firesrc.service.ScheduleExecutorManagerFactory;
import com.firesrc.service.SuperScheduledExecutorManager;

/**
 * Servlet implementation class ExecutorServlet
 */
public class ExecutorServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    handleSendMailThread(request);
    handleSearchMailThread(request);
    request.getRequestDispatcher("/executor.jsp").forward(request, response);
  }

  private void handleSendMailThread(HttpServletRequest request) {
    String operator = request.getParameter("operator");
    SuperScheduledExecutorManager searchMailExecutorManager = ScheduleExecutorManagerFactory.getSendMailExecutorManager();
    if ("start".equals(operator)) {
      searchMailExecutorManager.start();
    } else if ("stop".equals(operator)) {
      searchMailExecutorManager.stop();
      System.out.println("停止后台发邮件服务");
    }
    if (!searchMailExecutorManager.isShutdown()) {
      request.setAttribute("state", "1");
    } else {
      request.setAttribute("state", "0");
    }
  }

  private void handleSearchMailThread(HttpServletRequest request) {
    String operator = request.getParameter("searchoperator");
    SuperScheduledExecutorManager searchMailExecutorManager = ScheduleExecutorManagerFactory.getSearchMailExecutorManager();
    if ("searchstart".equals(operator)) {
      searchMailExecutorManager.start();
    } else if ("searchstop".equals(operator)) {
      searchMailExecutorManager.stop();
    }
    if (searchMailExecutorManager.isShutdown()) {
      request.setAttribute("searchstate", "0");
    } else {
      request.setAttribute("searchstate", "1");
    }
  }
}
